import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import configService from "@/api/services/configService";
import { StorageEnum } from "#/enum";

interface GlobalConfig {
  // 这里定义全局配置的类型
  [key: string]: any;
}

type ConfigStore = {
  globalConfig: GlobalConfig;
  actions: {
    setGlobalConfig: (config: GlobalConfig) => void;
    fetchGlobalConfig: () => Promise<void>;
  };
};

const useConfigStore = create<ConfigStore>()(
  persist(
    (set) => ({
      globalConfig: {},
      actions: {
        setGlobalConfig: (config) => {
          set({ globalConfig: config });
        },
        fetchGlobalConfig: async () => {
          try {
            const config = await configService.getGlobalConfig();
            set({ globalConfig: config });
          } catch (error) {
            console.error('Failed to fetch global config:', error);
          }
        },
      },
    }),
    {
      name: "configStore",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        [StorageEnum.GlobalConfig]: state.globalConfig,
      }),
    }
  )
);

// 导出常用的 hooks
export const useGlobalConfig = () => useConfigStore((state) => state.globalConfig);
export const useConfigActions = () => useConfigStore((state) => state.actions);

export default useConfigStore;
